package com.rules.admin.handler;

import com.gillion.grule.client.core.ValueType;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ValueTypeHandler implements TypeHandler<ValueType> {
   public void setParameter(PreparedStatement ps, int i, ValueType parameter, JdbcType jdbcType) throws SQLException {
      switch(parameter) {
      case Constant:
         ps.setInt(i, 0);
         break;
      case JDBC:
         ps.setInt(i, 1);
         break;
      case Service:
         ps.setInt(i, 2);
         break;
      case Rule:
         ps.setInt(i, 3);
         break;
      case InParameter:
         ps.setInt(i, 4);
         break;
      case Variable:
         ps.setInt(i, 5);
         break;
      case Dubbo:
         ps.setInt(i, 7);
         break;
      case SpringCloud:
         ps.setInt(i, 8);
      default:
         ps.setInt(i, 6);
      }

   }

   public ValueType getResult(ResultSet rs, String columnName) throws SQLException {
      int valueType = rs.getInt(columnName);
      return this.switchType(valueType);
   }

   public ValueType getResult(ResultSet rs, int columnIndex) throws SQLException {
      int valueType = rs.getInt(columnIndex);
      return this.switchType(valueType);
   }

   public ValueType getResult(CallableStatement cs, int columnIndex) throws SQLException {
      int valueType = cs.getInt(columnIndex);
      return this.switchType(valueType);
   }

   private ValueType switchType(int type) {
      switch(type) {
      case 0:
         return ValueType.Constant;
      case 1:
         return ValueType.JDBC;
      case 2:
         return ValueType.Service;
      case 3:
         return ValueType.Rule;
      case 4:
         return ValueType.InParameter;
      case 5:
         return ValueType.Variable;
      case 6:
      default:
         return ValueType.RemoteService;
      case 7:
         return ValueType.Dubbo;
      case 8:
         return ValueType.SpringCloud;
      }
   }
}
